package com.ihr360.commons.entityhandler;

import com.ihr360.commons.model.entity.TimeEntity;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.lang.reflect.InvocationTargetException;
import java.util.Calendar;

public class DateHandler {

    Logger logger = LoggerFactory.getLogger(DateHandler.class);

    @PrePersist
    void onPrePersist(Object o) {
        if (o == null) {
            return;
        }
        try {
            BeanUtils.copyProperty(o, TimeEntity.CREATE_AT, Calendar.getInstance().getTime());
        } catch (IllegalAccessException e1) {
            if (logger.isWarnEnabled()) {
                logger.warn(e1.getMessage(), e1);
            }
        } catch (InvocationTargetException e2) {
            if (logger.isWarnEnabled()) {
                logger.warn(e2.getMessage(), e2);
            }
        }
    }

    @PreUpdate
    void onPreUpldate(Object o) {
        if (o == null) {
            return;
        }
        try {
            BeanUtils.copyProperty(o, TimeEntity.UPDATE_AT, Calendar.getInstance().getTime());
        } catch (IllegalAccessException e1) {
            if (logger.isWarnEnabled()) {
                logger.warn(e1.getMessage(), e1);
            }
        } catch (InvocationTargetException e2) {
            if (logger.isWarnEnabled()) {
                logger.warn(e2.getMessage(), e2);
            }
        }
    }
}